package com.likai.jarscms.interceptor;

import java.text.SimpleDateFormat;
import java.util.TimeZone;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 日志拦截器
 * @author likai
 * @since 2018-03-29
 */
public class LogInterceptor implements HandlerInterceptor {
	
	private final Logger log = LoggerFactory.getLogger(getClass().getName());
	 
	private static final ThreadLocal<Long> startTimeThreadLocal = 
			new NamedThreadLocal<Long>("ThreadLocal StartTime");
	 

	/**
	 * 预处理
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		//开始时间 
		long beginTime = System.currentTimeMillis(); 
		 
		//线程绑定变量（该数据只有当前请求的线程可见） 
		startTimeThreadLocal.set(beginTime); 
		
		log.info("开始计时: {}", new SimpleDateFormat("HH:mm:ss.SSS").format(beginTime));
		log.info("访问地址：" + request.getRequestURI() + "，执行方式：" + request.getMethod());
		return true ;
	}

	/**
	 * 返回处理
	 */
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		if (modelAndView != null){
			log.info("ViewName: " + modelAndView.getViewName());

		}
	}

	/**
	 * 后处理
	 */
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// 输出日志信息	 
		//得到线程绑定的局部变量（开始时间） 
	    long beginTime = startTimeThreadLocal.get(); 
	    //结束时间 
	    long endTime = System.currentTimeMillis();	 
	    //设置时区
	    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS") ;
	    String a = sdf.format(endTime - beginTime) ;
	    sdf.setTimeZone(TimeZone.getTimeZone("GMT+0")) ;
		/*log.debug("计时结束：{}  URI: {}  最大内存: {}m  已分配内存: {}m  已分配内存中的剩余空间: {}m  最大可用内存: {}m",
				new SimpleDateFormat("hh:mm:ss.SSS").format(endTime),
				request.getRequestURI(), Runtime.getRuntime().maxMemory()/1024/1024, Runtime.getRuntime().totalMemory()/1024/1024, Runtime.getRuntime().freeMemory()/1024/1024,
				(Runtime.getRuntime().maxMemory()-Runtime.getRuntime().totalMemory()+Runtime.getRuntime().freeMemory())/1024/1024);*/
		log.info("计时结束: " + new SimpleDateFormat("HH:mm:ss.SSS").format(endTime));
		//删除线程变量中的数据，防止内存泄漏
        startTimeThreadLocal.remove();
	}

}
